//
// localSocket.js
// iodoxrfweb
//
// Created by 区区电脑 on 2023/06/08.
//


window.$localSocket = {
    callMethod,

    // 接收错误
    onError(error) {
        window.$message.error(error)
    },
    // 接收提示信息
    onMessage(message) {
        window.$message.success(message)
    },
}

// 调用后端方法
function callMethod(MethodName, Data) {
    window.chrome?.webview?.postMessage(JSON.stringify({MethodName, Data}));
}

// 注册前端桥接
window.chrome?.webview?.addEventListener("message", (arg) => {
    let res = arg.data;
    let MethodName = "";
    let Data = {};
    try {
        res = JSON.parse(res);
        MethodName = res.MethodName;
        Data = res.Data;
    } catch (e) {
        console.log(e);
    }
    if (window.$localSocket) {
        if (MethodName == "onError") {
            if (window.$localSocket.onError) {
                return window.$localSocket.onError(Data);
            }
        }
        if (window.$localSocket[MethodName]) {
            window.$localSocket[MethodName](Data);
        } else {
            console.warn("window.$localSocket.", MethodName, " 方法未注册");
        }
    } else {
        console.warn("window.$localSocket 初始化错误");
    }
});
